################################################################################
# File: browse.py
# Package: itacqos.uddi.views
# Author: Vincent Pretre
# Last update: $LastChangedDate: 2009-02-28 16:25:51 +0000 (Sat, 28 Feb 2009) $
################################################################################

##@package itacqos.uddi.views.browse
#
# This module contains all views about browsing the UDDI repository (finding services, displaying them, browsing categories ...)

from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

from uddi.models import Category, Keyword, WebService, Vendor, TestCategory, Verdict, Test
from uddi.forms import RegisterForm, UpdateUserForm, VendorForm, ServiceForm

from common import newRender, cleanKW, getUser, getMark, getServicesByCatOrKeyword, validationImg

import os
import urllib
import cStringIO

## Index of the site
def main(request):
    return newRender('main.html', {}, request)

## Display a single web service
def showService(request, serviceId):
	dict = {}

	# Gets the current user. It allows owner to see validation of his service
	# even if this one is hidden
	usr = getUser(request)

	# Get the asked WS
	ws = get_object_or_404(WebService, pk = serviceId)
	dict['service'] = ws

	# If the user is the owner of the displayed service, a menu is shown
	if usr['isAuthenticated'] and ws.producedBy.user == usr['user']:
		dict['userIsOwner'] = True
	# Else, if the service is hidden, a 404 error is raised
	elif not ws.public:
		raise Http404

	# Computes the two dictionnary defining notes (see uddi.views.common.py/getMark to understand definition of the dictionnaries )
	dict['unitaryMark'] = getMark(ws)
	dict['relationMark'] = getMark(ws, False)
	
	return newRender('showservice.html', dict, request)

## Returns an image which sums up service results
# @param serviceId Identifier of the service to display
def serviceImage(request, serviceId):
	service = get_object_or_404(WebService, pk = serviceId)
	
	operations = service.operation_set.all()
	tests = Test.objects.filter(operation__in=operations)
	nbTests = len(tests)
	
	validation = []
	
	for verdict in Verdict.objects.all():
		nbTestForVerdict = len(tests.filter(verdict = verdict))
		
		if nbTestForVerdict == 0:
			validation.append(0)
		else:
			validation.append((100 * nbTestForVerdict) / nbTests)
	
	img = validationImg(validation, 10, 1)
	
	#write to file object
	f = cStringIO.StringIO()
	img.save(f, "PNG")
	f.seek(0)
	
	return HttpResponse(f.read(), mimetype="image/png")

## Shows public profile of a vendor
# @param vendorId  Identifier of the vendor to display
def showVendor(request, vendorId):
	vendor = get_object_or_404(Vendor, pk = vendorId)
	services = vendor.webservice_set.filter(public = True)
	return newRender('showVendor.html', {'vendor' : vendor, 'services' : services}, request)

## Shows first page of the vendor's list
# @todo Create the function
def showVendorsP1(request):
	return showVendorsList(request, 1)

## Shows a page of the vendor's list
# @param page The requested page
# @todo Create the function
def showVendorsList(request, page):
	vendors = Vendor.objects.all()
	return HttpResponse("Vendors, page %s" % page)

## Shows first page of the services' list
# @todo Create the function
def showServicesP1(request):
	return showServicesList(request, 1)

## Shows services' list
# @param page The requested page
# @todo Create the function
def showServicesList(request, page):
	return HttpResponse("Services, page %s" % page)

## Advanced search form
# @todo Create the function
def searchForm(request):
	return HttpResponse("Coming soon")

## Computes search results
# @todo Create display
def results(request, req):
	askedWords = req.rsplit(" ")

	wss = WebService.objects.all()
	relevancyDict = {}

	for ws in wss:
		relevancyDict[ws] = 0
		for word in askedWords:
			if ws.name.lower().find(word.lower()) != -1:
				relevancyDict[ws] += 5
			
			if ws.desc.lower().find(word.lower()) != -1:
				relevancyDict[ws] += 2

	return newRender('searchResults.html', {'query' : req, 'services' : relevancyDict}, request)

## First page when browsing services by category
def showServicesByCatP1(request, category):
	return showServicesListByCat(request, category, 1)

## View used when browsing services by category
# @param category The category browsed
# @param page The requested page
def showServicesListByCat(request, category, page):
	cat = get_object_or_404(Category, slug=category)
	dict = getServicesByCatOrKeyword(cat, 10, int(page))
	
	dict['category'] = cat
	
	return newRender('showServicesByCat.html', dict, request)

## First page when browsing WS by keyword
def showServicesByKWP1(request, keyword):
	return showServicesListByKW(request, keyword, 1)

## View used when browsing services by keyword
# @param keyword The keyword browsed
# @param page THe requested page
def showServicesListByKW(request, keyword, page):
	kw = get_object_or_404(Keyword, slug=keyword)
	dict = getServicesByCatOrKeyword(kw, 10, int(page))
	
	dict['keyword'] = kw
	
	return newRender('showServicesByKW.html', dict, request)

## Help page
# @todo Create the function
def help(request):
    return HttpResponse("Help, I need somebody's help ...")


